package validation

import (
	ut "github.com/go-playground/universal-translator"
	"gopkg.in/go-playground/validator.v9"
	"regexp"
)

type FrontValidator struct {
	BaseValidator
}

func NewFrontValidator() *FrontValidator {
	valid := &FrontValidator{}
	valid.initValidator()
	return valid
}

//自定义验证函数
func (fv *FrontValidator) UsernameValidFunc(fl validator.FieldLevel) bool {
	isMatched, _ := regexp.MatchString("^[\\w]{1,}$", fl.Field().String())
	return isMatched
}

//自定义验证函数
func (fv *FrontValidator) phoneValidFunc(fl validator.FieldLevel) bool {
	isMatched, _ := regexp.MatchString("^[0-9]{11}$", fl.Field().String())
	return isMatched
}

//自定义标签
func (fv *FrontValidator) RegCustomTag() {
	//注册自己的验证函数
	fv.MyValidtor.RegisterValidation("phone", fv.phoneValidFunc)
	fv.MyValidtor.RegisterValidation("username", fv.UsernameValidFunc)
	//注册对应的翻译器
	fv.MyValidtor.RegisterTranslation("username", fv.trans, func(ut ut.Translator) error {
		return ut.Add("username", "{0} 只能由字母和数字组成!", true) // see universal-translator for details
	}, func(ut ut.Translator, fe validator.FieldError) string {
		t, _ := ut.T("username", fe.Field())

		return t
	})

	//注册对应的翻译器
	fv.MyValidtor.RegisterTranslation("phone", fv.trans, func(ut ut.Translator) error {
		return ut.Add("phone", "{0} 只能是11位的数字!", true) // see universal-translator for details
	}, func(ut ut.Translator, fe validator.FieldError) string {
		t, _ := ut.T("phone", fe.Field())

		return t
	})
}
